package com.changgou.order.controller;

import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.pay.feign.PayFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
@RequestMapping("/wxpay")
public class PayController {

    @Autowired
    private PayFeign payFeign;

    @Autowired
    private OrderFeign orderFeign;


    /**
     * 跳转到支付页面
     * @param orderId
     * @param model
     * @return
     */
    @GetMapping
    public String wxPay(String orderId, Model model){

        //1.根据orderId查询订单，如果订单不存在，跳转到错误页面
        Order order = orderFeign.findById(orderId).getData();
        if (order == null){
            return "fail";
        }

        //2.根据订单的支付状态进行判断，如果不是未支付的订单，跳转到错误页面
        if (!"0".equals(order.getPayStatus())){
            return "fail";
        }

        //3.基于payFeign调用统计下单接口，并获取返回结果
        Object data = payFeign.nativePay(orderId, order.getPayMoney()).getData();

        if (data == null){
            return "fail";
        }

        //4.封装结果数据(二维码，订单id，应付金额)
        Map payResult = (Map) data;//内含二维码，还需封装订单id和应付金额
        payResult.put("orderId",orderId);
        payResult.put("payMoney",order.getPayMoney());

        model.addAllAttributes(payResult);

        return "wxpay";
    }



    @GetMapping("/topaysuccess")
    public String topaysuccess(Integer payMoney,Model model){
        model.addAttribute("payMoney",payMoney);
        return "paysuccess";
    }
}
